package com.yxh.activity;

import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicInteger;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout.LayoutParams;

import com.yxh.R;
import com.yxh.ZybApplication;
import com.yxh.dto.UserDto;
import com.yxh.service.DataService;
import com.yxh.service.Task;
import com.yxh.util.LogUtil;
import com.yxh.view.KeyboardLayout;

/**
 * 登录界面
 * 
 * @author luoming
 * 
 */

public class UserLoginActivity extends BaseActivity implements OnClickListener {

	private KeyboardLayout pLayout;
	private View bottomParentView, bootomItemView;
	private EditText phoneEt, codeEt;
	private Button loginBtn, codeBtn;
	private String source; // 0:loading 1:guide 2: aboutsetting

	private final int targetInfoTopMargin = ZybApplication.getContext()
			.getResources()
			.getDimensionPixelSize(R.dimen.user_login_info_margin_top);
	private final int targetInfoTopMarginFocused = ZybApplication.getContext()
			.getResources()
			.getDimensionPixelSize(R.dimen.user_login_info_margin_top_focused);
	private volatile boolean input_state = false; // 键盘状态
	private volatile boolean can_animation = false;// 动画开启

	private LinkedList<Integer> mAnimatingList = new LinkedList<Integer>();
	private AtomicInteger mAnimatingIdGen = new AtomicInteger();

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_user_login);

		source = getIntent().getStringExtra("source");

		initView();

		overridePendingTransition(R.anim.enter_righttoleft, R.anim.noanim);
	}

	private void initView() {
		pLayout = (KeyboardLayout) findViewById(R.id.user_login_playout);
		bottomParentView = findViewById(R.id.user_login_bottom_playout);
		bootomItemView = findViewById(R.id.user_login_bottom_layout);
		phoneEt = (EditText) findViewById(R.id.user_login_phone_et);
		codeEt = (EditText) findViewById(R.id.user_login_code_et);
		codeBtn = (Button) findViewById(R.id.user_code_btn);
		loginBtn = ((Button) findViewById(R.id.user_login_btn));

		pLayout.setOnClickListener(this);
		codeBtn.setOnClickListener(this);
		loginBtn.setOnClickListener(this);
		bootomItemView.setOnClickListener(this);

		pLayout.setOnResizeListener(new KeyboardLayout.OnResizeListener() {
			public void OnResize(int w, int h, int oldw, int oldh) {
				if (!can_animation) {
					return;
				}
				if (h < oldh) {
					LogUtil.e("打开");
					input_state = true;
					openState();
				} else {
					LogUtil.e("关闭");
					input_state = false;
					closedState();
				}
			}
		});

		// LogUtil.e("onCreate");

		handler.sendEmptyMessageDelayed(START_CAN_ANIMATION, 1000);

	}

	@Override
	public void onClick(View view) {
		int id = view.getId();
		if (id == R.id.user_code_btn) {
			goGetCode();
		} else if (id == R.id.user_login_btn) {
			goLogin();
		} else if (id == R.id.user_login_playout) {
			if (input_state) {
				closedInput();
			}
		} else if (id == R.id.user_login_bottom_layout) {
			goAgrreeMent();
		}
	}

	@Override
	protected void onStart() {
		super.onStart();
		// LogUtil.e("source -->" + source);
		// LogUtil.e("equals -- 2 -->" + "source".equals("2"));
		// if ("2".equals(source)) {
		// int num = 0;
		// Iterator<Activity> iterator = MainService.allActivity.iterator();
		// while (iterator.hasNext()) {
		// Activity ac = (Activity) iterator.next();
		// LogUtil.e("ac.getClass -->"
		// + ac.getClass().getName().indexOf("UserLoginActivity"));
		// if (ac.getClass().getName().indexOf("UserLoginActivity") <= 0) {
		// iterator.remove();
		// }
		// num++;
		// }
		// }

	}

	private String phone, code;

	/** 获取验证码 **/
	private void goGetCode() {
		phone = String.valueOf(phoneEt.getText());
		if (TextUtils.isEmpty(phone)) {
			showToast("手机号码不能为空");
			phoneEt.setFocusable(true);
			return;
		}

		if ((phone.length() != 11)) {
			showToast("请输入正确的手机号码(11位)");
			phoneEt.setFocusable(true);
			return;
		}

		closedInput();

		Message msg = handler.obtainMessage(GET_CODE);
		handler.sendMessageDelayed(msg, 300);
	}

	/** 登录 **/
	private void goLogin() {
		phone = String.valueOf(phoneEt.getText());
		code = String.valueOf(codeEt.getText());
		if (TextUtils.isEmpty(phone)) {
			showToast("手机号码不能为空");
			phoneEt.setFocusable(true);
			return;
		}

		if ((phone.length() != 11)) {
			showToast("请输入正确的手机号码(11位)");
			phoneEt.setFocusable(true);
			return;
		}

		if (TextUtils.isEmpty(code)) {
			showToast("验证码不能为空");
			codeEt.setFocusable(true);
			return;
		}

		closedInput();

		Message msg = handler.obtainMessage(LOGIN_USER);
		handler.sendMessageDelayed(msg, 300);

	}

	private void goAgrreeMent() {
		Intent it = new Intent(mContext, WebViewActivity.class);
		it.putExtra("title", "用户协议");
		it.putExtra("url", "file:///android_asset/userAgreement.html");
		startActivity(it);
	}

	@Override
	public void refresh(Object... param) {
		try {
			int operType = (Integer) param[0];
			Object obj = param[1];
			closeDialog();
			switch (operType) {
			case Task.LOGIN_USER: {
				UserDto dto = (UserDto) obj;
				Intent it = new Intent(mContext, MainActivity.class);
				startActivity(it);
				finish();
			}
				// if (dto != null) {
				// if (DataService.DATA_SUCCESS.equals(dto.result)) {
				// db.modifyConfigItem("uid", dto.uid);
				// db.insertUserInfo(dto);
				// showToast("恭喜登录成功");
				// if ("0".equals(source) || "1".equals(source)
				// || "2".equals(source)) {
				// Intent it = new Intent(mContext, MainActivity.class);
				// startActivity(it);
				// finish();
				// }
				// } else {
				// showToast(dto.message);
				// }
				// } else {
				// showToast(getString(R.string.http_no_net_tip));
				// }
				break;

			case Task.GET_CODE:
				UserDto dto = (UserDto) obj;
				if (dto != null) {
					if (DataService.DATA_SUCCESS.equals(dto.result)) {
						Message msg = handler.obtainMessage(REFUSH_TIME);
						msg.arg1 = 60;
						handler.sendMessage(msg);
						showToast("发送验证码成功，请在邮箱查看");
					} else {
						showToast(dto.message);
					}
				} else {
					showToast(R.string.http_no_net_tip);
				}
				break;

			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void openState() {

		LayoutParams lp = (LayoutParams) pLayout.getLayoutParams();
		final int curInfoTopMargin = lp.topMargin;
		LogUtil.e("targetInfoTopMargin 1-->" + targetInfoTopMargin);
		LogUtil.e("curInfoTopMargin 1-->" + curInfoTopMargin);
		LogUtil.e("targetInfoTopMargin 1-->"
				+ (targetInfoTopMargin - curInfoTopMargin));
		lp.topMargin = targetInfoTopMargin;
		pLayout.setLayoutParams(lp);
		Animation up = new TranslateAnimation(0, 0, (float) targetInfoTopMargin
				- curInfoTopMargin, 0);
		up.setInterpolator(new AccelerateInterpolator());
		up.setDuration(350L);
		pLayout.startAnimation(up);
		bottomParentView.setVisibility(View.INVISIBLE);
	}

	private void closedState() {

		LayoutParams lp = (LayoutParams) pLayout.getLayoutParams();
		final int curInfoTopMargin = lp.topMargin;
		lp.topMargin = -targetInfoTopMarginFocused;
		LogUtil.e("targetInfoTopMargin 2-->" + targetInfoTopMarginFocused);
		LogUtil.e("curInfoTopMargin 2-->" + curInfoTopMargin);
		LogUtil.e("targetInfoTopMargin 2-->"
				+ (curInfoTopMargin - targetInfoTopMarginFocused));
		pLayout.setLayoutParams(lp);
		Animation down = new TranslateAnimation(0, 0, (float) curInfoTopMargin
				- targetInfoTopMarginFocused, 0);
		down.setInterpolator(new DecelerateInterpolator());
		down.setDuration(350L);
		down.setAnimationListener(new MyAnimationListener() {
			@Override
			public void onAnimationEnd(Animation animation) {
				super.onAnimationEnd(animation);
			}

			@Override
			public void onAnimationStart(Animation animation) {
				super.onAnimationStart(animation);
				bottomParentView.setVisibility(View.VISIBLE);
			}
		});
		pLayout.startAnimation(down);
	}

	private class MyAnimationListener extends EmptyAnimationListener {
		final int animId = mAnimatingIdGen.incrementAndGet();

		@Override
		public void onAnimationStart(Animation animation) {
			mAnimatingList.add(animId);
			handler.sendMessageDelayed(
					handler.obtainMessage(MSGID_TIMEOUT_ANIMATION, animId, 0),
					animation.getDuration());
		}

		@Override
		public void onAnimationEnd(Animation animation) {
			mAnimatingList.remove(Integer.valueOf(animId));
		}
	}

	class EmptyAnimationListener implements AnimationListener {

		@Override
		public void onAnimationStart(Animation animation) {
		}

		@Override
		public void onAnimationEnd(Animation animation) {
		}

		@Override
		public void onAnimationRepeat(Animation animation) {
		}

	}

	private final static int REFUSH_TIME = 0;
	private static final int MSGID_TIMEOUT_ANIMATION = 1;
	private final static int START_CAN_ANIMATION = 2;
	private final static int GET_CODE = 3; // 获取验证码
	private final static int LOGIN_USER = 4;// 登录
	private Handler handler = new Handler(Looper.getMainLooper()) {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == REFUSH_TIME) {
				int tc = msg.arg1;
				tc--;
				if (tc >= 0) {
					codeBtn.setText(String.format("已发送(%ds)", tc));
					codeBtn.setTextColor(Color.parseColor("#bfbfbf"));
					codeBtn.setEnabled(false);
					Message m = handler.obtainMessage(REFUSH_TIME);
					m.arg1 = tc;
					handler.sendMessageDelayed(m, 1000);
				} else {
					codeBtn.setText("获取验证码");
					codeBtn.setTextColor(Color.parseColor("#8e8e8e"));
					codeBtn.setEnabled(true);
				}
			} else if (msg.what == MSGID_TIMEOUT_ANIMATION) {
				mAnimatingList.remove(Integer.valueOf(msg.arg1));
			} else if (msg.what == START_CAN_ANIMATION) {
				LogUtil.e("START_CAN_ANIMATION");

				can_animation = true;
				LayoutParams lp = (LayoutParams) pLayout.getLayoutParams();
				lp.topMargin = -targetInfoTopMarginFocused;
			} else if (msg.what == GET_CODE) {
				// mobile_No（手机号，必填）、device_code（设备码，必填）
				LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
				map.put("s", "main/get_sms_captcha");
				map.put("mobile_No", phone);
				getData(map, Task.GET_CODE);
			} else if (msg.what == LOGIN_USER) {
				// captcha（验证码，必填）、mobile_No（手机号，必填）、device_code（设备码，必填）
				LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
				map.put("s", "account/nopwd_login");
				map.put("mobile_No", phone);
				map.put("captcha", code);
				getData(map, Task.LOGIN_USER);

			}
		}
	};

	private void closedInput() {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(pLayout.getWindowToken(), 0);
	}

	protected void onDestory() {
		if (handler != null) {
			handler.removeMessages(REFUSH_TIME);
		}
		super.onDestroy();
	};

}